#!/bin/bash
# arglist.sh
# Invoke this script with several arguments, such as "one two three".

E_BADARGS=65

# test the differences between $* and $@
# $* treats all the parameters ras a single word (if it is quoted)
# $@ treats all the parameters as separate words even it is quoted.
testParameter1()
{
    if [ ! -n "$1" ]
    then
        echo "testParameter1 needs more than one arguments."
        return $E_BADARGS
    fi

index=1     # Initialize count.
echo "Listing args with \"\$*\":"
for arg in "$*"     # Doesn't work properly if "$*" isn't quoted.
do
    echo "Arg #$index = $arg"
    let "index+=1"
done                # $* sees all arguments as single word.

echo "Entire arg list seen as single word."
echo

index=1 # Reset count.
# What happens if you forget to do this?
echo "Listing args with \"\$@\":"
for arg in "$@"
do
    echo "Arg #$index = $arg"
    let "index+=1"
done # $@ sees arguments as separate words.
echo "Arg list seen as separate words."

echo
index=1 # Reset count.
echo "Listing args with \$* (unquoted):"
for arg in $*
do
    echo "Arg #$index = $arg"
    let "index+=1"
done # Unquoted $* sees arguments as separate words.
echo "Arg list seen as separate words."
exit 0
}

#  test parameter subsititution
#  ${parameter-default},${parameter:-default}: use default if parameter
#+ is not set (: one also effective when the parameter is zero in length
#+ but parameter will keep the original state (unset) after.
#  ${parameter=dafault},${parameter:=default}: use default and set the 
#+ value of default to parameter
testParameter2()
{
    # Normal usage
    echo "username = ${username-`whoami`}"
    echo "username = $username"		#not set
    default_username=`whoami`
    echo "default_username = $default_username"
    echo "username = ${username-$default_username}"	#display the value of default_username
    echo "username = $uaername"

    # Different between - and :-
    username=
    echo "username = ${username-`whoami`}"
    echo "username = ${username:-`whoami`}"
    
}

testParameter3()
{
    : ${1?"Usage: $0 ARGUMENT"}
    echo "reaching here means you provide the parameter to the function"
    echo "command line parameter = \"$1\""
    
    return 0;
}

#Main

#testParameter1 abc bcd edf
#testParameter2
testParameter3 abc
testParameter3
rc=$?
echo "$0 exits with $?"
return $rc
